package com.mapscloud.bottomnavi.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceView;

public class AutoFitSurfaceView extends SurfaceView {

    private static final String TAG = AutoFitSurfaceView.class.getSimpleName();
    private float aspectRatio = 0f;

    public AutoFitSurfaceView(Context context) {
        super(context, null, 0);
    }

    public AutoFitSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
    }

    public AutoFitSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setAspectRatio(int width, int height) {
        if (width > 0 && height > 0) {
            aspectRatio = (float) width / (float) height;
            getHolder().setFixedSize(width, height);
            requestLayout();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        Log.d(TAG, "onMeasure:" + width + " x " + height);

        if (aspectRatio == 0f) {
            setMeasuredDimension(width, height);
        } else {
            int newWidth;
            int newHeight;
            float actualRatio = width > height ? aspectRatio : 1 / aspectRatio;
            if (width < height * actualRatio) {
                newHeight = height;
                newWidth = Math.round(height * actualRatio);
            } else {
                newWidth = width;
                newHeight = Math.round(width / actualRatio);
            }

            Log.d(TAG, "Measured dimensions set:" + newWidth + " x " + newHeight);
            setMeasuredDimension(newWidth, newHeight);
        }
    }
}
